<template>
    <el-dialog v-model="manageOrderFileVisible" :show-close="false" fullscreen>
        <!-- 自定义头部 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">管理订单文件 -- ESC关闭</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>

        <el-descriptions title="受控列表" :column="3" border>
            <div v-for="(item, index) in props.orderFileData" :key="index">
                <!-- 源文件 -->
                <el-descriptions-item>
                    <template #label>
                        <div class="flex items-center gap-2">
                            <el-icon>
                                <FileAnalytics />
                            </el-icon>
                            源文件
                        </div>
                    </template>
                    {{ item.originalFileName }}
                </el-descriptions-item>
                <!-- 回传文件 -->
                <el-descriptions-item>
                    <template #label>
                        <div class="flex items-center gap-2">
                            <el-icon>
                                <FileCheck />
                            </el-icon>
                            回传文件
                        </div>
                    </template>
                    {{ item.passBackFileName ? item.passBackFileName : '/' }}
                </el-descriptions-item>
                <!-- 管理 -->
                <el-descriptions-item>
                    <template #label>
                        <div class="flex items-center gap-2">
                            <el-icon>
                                <ManageProtection />
                            </el-icon>
                            管理
                        </div>
                    </template>
                    <div class="flex items-center">
                        <!-- 上传 -->
                        <el-dropdown>
                            <span class="el-dropdown-link mr-4">
                                上传
                                <el-icon class="el-icon--right">
                                    <CloudUpload />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <!-- 上传源文件 -->
                                    <el-dropdown-item>
                                        <el-upload
                                            ref="uploadOriginalOrderFileRef"
                                            name="file"
                                            accept=".jpeg,.jpg,.png,.webp,.dpf,.doc,.docx,.xls,.xlsx"
                                            with-credentials
                                            :action="orderFileAction"
                                            :data="{
                                                customerName: props.customerName,
                                                fileName: props.fileName,
                                                orderId: props.orderId,
                                                index: index,
                                                newOrderFile: false,
                                                orderPassBack: false,
                                                creator: useUserStore().username,
                                                creatorId: useUserStore().id,
                                            }"
                                            :limit="1"
                                            :on-change="handleOrderFileChangeEvent"
                                            :on-exceed="handleOrderFileExceedEvent"
                                            :on-progress="uploadOrderFileProgressEvent"
                                            :on-success="uploadOrderFileSuccessEvent"
                                            :on-error="uploadOrderFileErrorEvent"
                                        >
                                            <el-button type="primary" text :icon="CircuitComposer">源文件</el-button>
                                        </el-upload>
                                    </el-dropdown-item>
                                    <!-- 上传回传文件 -->
                                    <el-dropdown-item>
                                        <el-upload
                                            ref="uploadPassBackOrderFileRef"
                                            name="file"
                                            :action="orderFileAction"
                                            with-credentials
                                            :data="{
                                                customerName: props.customerName,
                                                fileName: props.fileName,
                                                orderId: props.orderId,
                                                index: index,
                                                newOrderFile: false,
                                                orderPassBack: true,
                                                creator: useUserStore().username,
                                                creatorId: useUserStore().id,
                                            }"
                                            :limit="1"
                                            :on-change="handlePassBackOrderFileChangeEvent"
                                            :on-exceed="handlePassBackOrderFileExceedEvent"
                                            :on-progress="uploadPassBackOrderFileProgressEvent"
                                            :on-success="uploadPassBackOrderFileSuccessEvent"
                                            :on-error="uploadPassBackOrderFileErrorEvent"
                                        >
                                            <el-button type="primary" text :icon="Classification">回传件</el-button>
                                        </el-upload>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <!-- 下载 -->
                        <el-dropdown>
                            <span class="el-dropdown-link mr-4">
                                下载
                                <el-icon class="el-icon--right">
                                    <CloudDownload />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <!-- 下载源文件 -->
                                    <el-dropdown-item>
                                        <el-button
                                            type="primary"
                                            text
                                            :icon="CircuitComposer"
                                            @click="downloadOriginalOrderFile(item.originalfileUrl)"
                                        >
                                            源文件
                                        </el-button>
                                    </el-dropdown-item>
                                    <!-- 下载回传文件 -->
                                    <el-dropdown-item>
                                        <el-button
                                            type="primary"
                                            text
                                            :icon="Classification"
                                            @click="downloadPassBackOrderFile(item.passBackfileUrl)"
                                        >
                                            回传件
                                        </el-button>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <!-- 删除 -->
                        <el-dropdown>
                            <span class="el-dropdown-link">
                                删除
                                <el-icon class="el-icon--right">
                                    <Delete28Regular />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <!-- 删除源文件 -->
                                    <el-dropdown-item>
                                        <el-button
                                            type="primary"
                                            text
                                            :icon="CircuitComposer"
                                            @click="deleteOrderFileEvent(props.orderId, index, 'original')"
                                        >
                                            源文件
                                        </el-button>
                                    </el-dropdown-item>
                                    <!-- 删除回传文件 -->
                                    <el-dropdown-item>
                                        <el-button
                                            type="primary"
                                            text
                                            :icon="Classification"
                                            @click="deleteOrderFileEvent(props.orderId, index, 'passback')"
                                        >
                                            回传件
                                        </el-button>
                                    </el-dropdown-item>
                                    <!-- 删除所有文件 -->
                                    <el-dropdown-item>
                                        <el-button type="primary" text :icon="ClearAll" @click="deleteOrderFileEvent(props.orderId, index, 'all')">
                                            全部件
                                        </el-button>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </el-descriptions-item>
            </div>
        </el-descriptions>
    </el-dialog>
</template>

<script setup lang="ts">
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { Delete28Regular } from '@vicons/fluent';
import { FileAnalytics, FileCheck, ClearAll } from '@vicons/tabler';
import { ManageProtection, CloudUpload, CloudDownload, CircuitComposer, Classification } from '@vicons/carbon';
import { useUserStore } from '@store/modules/user';
import { HttpUrl } from '@/api/httpUrl';
import { genFileId, UploadFile, UploadFiles, UploadInstance, UploadProgressEvent, UploadProps, UploadRawFile } from 'element-plus';
import { bytesToMB } from '@/utils/calculate';
import { deleteOrderFile } from '@/api/order';

/* ******************************通用属性/方法****************************** */
// model 声明
// 上传订单文件弹窗开关
const manageOrderFileVisible = defineModel('manageOrderFileVisible', { type: Boolean, default: false, required: true });

// props 声明
const props = defineProps<{ orderFileData: AjaxResponse['orderList'][0]['orderFiles']; orderId: string; customerName: string; fileName: string }>();

// 订单文件上传地址
const orderFileAction = ref(import.meta.env.VITE_APP_UPLOAD_URL + import.meta.env.VITE_APP_BASE_API + HttpUrl.uploadOrderFile);

/* ******************************下载订单文件的属性/方法****************************** */
const downloadOriginalOrderFile = (url: string) => {
    window.open(import.meta.env.VITE_APP_SERVER_URL + url);
};
const downloadPassBackOrderFile = (url: string) => {
    window.open(import.meta.env.VITE_APP_SERVER_URL + url);
};
/* ******************************删除订单文件的属性/方法****************************** */
const deleteOrderFileEvent = (orderId: string, index: number, type: string) => {
    deleteOrderFile(orderId, index, type).then(() => {
        ElMessage({
            message: '删除成功',
            type: 'success',
            grouping: true,
        });
        // 更新订单文件列表
        manageOrderFileVisible.value = false;
    });
};

/* ******************************上传订单源文件的属性/方法****************************** */
// 上传更换源文件
const uploadOriginalOrderFileRef = ref<UploadInstance>();
// 订单文件发生变化时触发 文件类型验证  文件大小验证
const handleOrderFileChangeEvent = (uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    // 验证文件大小
    if (bytesToMB(uploadFile.size as number) > 20) {
        ElMessage({
            message: '文件大小不能超过20MB',
            type: 'warning',
            grouping: true,
        });
        uploadOriginalOrderFileRef.value!.clearFiles();
    }

    // 验证文件类型
    if (
        !(
            uploadFile.raw?.type == 'image/jpg' ||
            uploadFile.raw?.type == 'image/jpeg' ||
            uploadFile.raw?.type == 'image/png' ||
            uploadFile.raw?.type == 'image/webp' ||
            uploadFile.raw?.type == 'application/pdf' ||
            uploadFile.raw?.type == 'application/msword' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
            uploadFile.raw?.type == 'application/vnd.ms-excel' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    ) {
        ElMessage({
            message: '不支持的文件类型',
            type: 'warning',
            grouping: true,
        });
        uploadOriginalOrderFileRef.value!.clearFiles();
    }
};
// 再次拖拽/上传时覆盖前一个订单文件
const handleOrderFileExceedEvent: UploadProps['onExceed'] = (files) => {
    uploadOriginalOrderFileRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadOriginalOrderFileRef.value!.handleStart(file);
};
// 订单文件上传时的回调
const uploadOrderFileProgressEvent = (evt: UploadProgressEvent, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    console.log(evt);
};
// 订单文件成功上传的回调
const uploadOrderFileSuccessEvent = (response: any, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: response.message,
        type: 'success',
        grouping: true,
    });
    manageOrderFileVisible.value = false;
};
// 订单文件上传失败的回调
const uploadOrderFileErrorEvent = (_err: Error, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: '上传失败',
        type: 'error',
        grouping: true,
    });
};

/* ******************************上传订单回传件的属性/方法****************************** */
// 上传更换回传件
const uploadPassBackOrderFileRef = ref<UploadInstance>();
// 订单文件发生变化时触发 文件类型验证  文件大小验证
const handlePassBackOrderFileChangeEvent = (uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    // 验证文件大小
    if (bytesToMB(uploadFile.size as number) > 20) {
        ElMessage({
            message: '文件大小不能超过20MB',
            type: 'warning',
            grouping: true,
        });
        uploadPassBackOrderFileRef.value!.clearFiles();
    }

    // 验证文件类型
    if (
        !(
            uploadFile.raw?.type == 'image/jpg' ||
            uploadFile.raw?.type == 'image/jpeg' ||
            uploadFile.raw?.type == 'image/png' ||
            uploadFile.raw?.type == 'image/webp' ||
            uploadFile.raw?.type == 'application/pdf' ||
            uploadFile.raw?.type == 'application/msword' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
            uploadFile.raw?.type == 'application/vnd.ms-excel' ||
            uploadFile.raw?.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    ) {
        ElMessage({
            message: '不支持的文件类型',
            type: 'warning',
            grouping: true,
        });
        uploadPassBackOrderFileRef.value!.clearFiles();
    }
};
// 再次拖拽/上传时覆盖前一个订单文件
const handlePassBackOrderFileExceedEvent: UploadProps['onExceed'] = (files) => {
    uploadPassBackOrderFileRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadPassBackOrderFileRef.value!.handleStart(file);
};
// 订单文件上传时的回调
const uploadPassBackOrderFileProgressEvent = (evt: UploadProgressEvent, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    console.log(evt);
};
// 订单文件成功上传的回调
const uploadPassBackOrderFileSuccessEvent = (response: any, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: response.message,
        type: 'success',
        grouping: true,
    });
    manageOrderFileVisible.value = false;
};
// 订单文件上传失败的回调
const uploadPassBackOrderFileErrorEvent = (_err: Error, _uploadFile: UploadFile, _uploadFiles: UploadFiles) => {
    ElMessage({
        message: '上传失败',
        type: 'error',
        grouping: true,
    });
};
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}
</style>
